import { Injectable, UnauthorizedException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { Strategy } from "passport-local";

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
    constructor() {
        // 可配置 passport 的策略行为
        super({
            usernameField: "username", // local 策略（账号-密码验证）默认的前端参数名为 username 和 password
            // usernameField: "email", // 如果是邮箱作为账号验证，则可如此配置
            passwordField: "password"
        });
    }

    // 固定函数签名的验证方法
    async validate(username: string, password: string): Promise<any> {
        // 验证用户信息
        // const user = await this.authService.validateUser(username, password);
        let user = null;
        if (username === "admin" && password === "admin123") {
            user = {
                username,
                password,
                roles: ["admin"]
            };
        }
        if (!user) {
            throw new UnauthorizedException();
        }
        return user;
    }
}
